package com.sumer.psychology.space.infrastructure.persistence.mongo;

import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import com.sumer.psychology.common.domain.model.User;
import com.sumer.psychology.common.domain.model.UserService;
import com.sumer.psychology.sharing.domain.model.SharedResource;
import com.sumer.psychology.space.domain.MessageType;
import com.sumer.psychology.space.infrastructure.port.adapter.SharedResourceAdaptor;

/**
 * Mongo Recommendation
 * <p/>
 * Created by zhu on 14/12/7.
 */
public class MongoRecommendationRepository extends MongoMessageRepository {
    private SharedResourceAdaptor sharedResourceAdaptor;
    private UserService userService;

    @Override
    public void add(String data) {
        DBObject message = initializeCreateData(data, "from.identity");
        String proposerId = (String) message.get("_id");
        String friendId = nestedValue(message, "to.identity");
        String sharedId = nestedValue(message, "sharedResourceId.identity");
        message.removeField("to");
        message.removeField("sharedResourceId");

        SharedResource sharedResource = sharedResourceAdaptor().sharedResource(sharedId);
        User proposer = userService().userFrom(proposerId);
        User friend = userService().userFrom(friendId);

        message.put("owner_name", proposer.name());

        update(message, message(sharedResource, proposer, friend));

        message.put("_id", friendId);
        message.put("owner_name", friend.name());
        update(message, message(sharedResource, proposer, friend));
    }

    private DBObject message(SharedResource sharedResource, User proposer, User friend) {
        return new BasicDBObject("resource", resource(sharedResource))
                .append("proposer", userToDB(proposer))
                .append("friend", userToDB(friend))
                .append("messageType", MessageType.RECOMMENDATION.toString());
    }

    private BasicDBObject resource(SharedResource sharedResource) {
        return new BasicDBObject()
                .append("identity", sharedResource.sharedResourceId().identity())
                .append("name", sharedResource.topic());
    }

    private DBObject userToDB(User user) {
        return new BasicDBObject("identity", user.identity()).append("name", user.name());
    }

    public void setSharedResourceAdaptor(SharedResourceAdaptor sharedResourceAdaptor) {
        this.sharedResourceAdaptor = sharedResourceAdaptor;
    }

    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    private SharedResourceAdaptor sharedResourceAdaptor() {
        return sharedResourceAdaptor;
    }

    private UserService userService() {
        return userService;
    }
}
